import { useEffect, useState } from 'react'
import { useDebounceEffect } from 'ahooks'
import { usePendingStore } from './store'
import shallow from 'zustand/shallow'

export interface ISearchDetail {
	isSearch: boolean
	searchType: null | 1 | 2
	totalNum: number
}
export type ISearchService = ReturnType<typeof useSearch>
export const useSearch = () => {
	const { fetchInit, fetchSimpleSearch, fetchAllSearch } = usePendingStore(
		(state) => ({
			fetchInit: state.fetchInit,
			fetchSimpleSearch: state.fetchSimpleSearch,
			fetchAllSearch: state.fetchAllSearch,
		}),
		shallow
	)
	const [searchVal, setSearchVal] = useState('')
	const [actualSearchVal, setActualSearchVal] = useState('')
	const handleSearch = (val: string) => {
		setSearchVal(val)
		setActualSearchVal(val.trim())
	}
	useEffect(() => {
		if (actualSearchVal === '') {
			fetchInit()
		}
	}, [actualSearchVal])
	useDebounceEffect(
		() => {
			if (actualSearchVal.match(/<|>|"|'|\//gi)) return
			if (actualSearchVal !== '') {
				fetchSimpleSearch(actualSearchVal)
			}
		},
		[actualSearchVal],
		{
			wait: 500,
		}
	)
	const handleAllSearch = async () => {
		if (actualSearchVal.match(/<|>|"|'|\//gi)) return
		fetchAllSearch(actualSearchVal)
	}
	return { value: searchVal, actualSearchVal, searchAll: handleAllSearch, onSearch: handleSearch }
}
